/*
 * ConfigurableEndsWithFileFilter.java
 * 
 * Copyright (C) 2009 no.good.at.coding
 * 
 * This file is part of the NoGoodCommons Library.
 *
 * The NoGoodCommons Library is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.nogoodatcoding.commons;

import java.io.File;
import java.io.FileFilter;
import org.apache.log4j.Logger;

/**
 *
 * Implements a {@link FileFilter} based on the string passed to the constructer.
 *
 * The string can be an extension or a list of pipe separated values of
 * extensions (because pipes are not allowed in the filenames (AFAIK!)).
 *
 * (Can also be used for non-extension checking but keep in mind that
 * the {@code accept()} method essentially checks if the filename ends with
 * the given value)
 *
 * @author no.good.at.coding
 */
public class ConfigurableEndsWithFileFilter
        implements FileFilter
{
    private static Logger log = Logger.getLogger(ConfigurableEndsWithFileFilter.class);

    private String [] arrayOfExtensions = null;

    private boolean includeFolders = true;
    private boolean isCaseSensitive = true;

    /**
     *
     * Returns a new {@code ConfigurableEndsWithFileFilter} object if the
     * extensions given are non null and not empty/whitespace. If they are, a
     * null is returned to avoid the overhead of calling {@code accept()} when
     * we know all files will match
     *
     * @param extensions A list of PSV (pipe separated values) of extensions
     * that should be accepted by this filter. If it's null/empty/only
     * whitespace, a null will be returned. Any whitespace before and after the
     * pipe will be ignored. The extensions should not be in the format of
     * {@code *.avi|*.txt|*.java} etc. The asterisks and period symbols will
     * treated as literals. Use the format {@code avi|txt|java} instead.
     *
     * @param includeFolders Indicates if folders will be accepted or not
     * @param isCaseSensitive Indicates if the matches will be case sensitive or
     *                        not (keep in mind *nix sytems when setting to
     *                        {@code false})
     *
     * @return null if extensions is null or empty; a 
     *         {@code ConfigurableEndsWithFileFilter} object otherwise
     *
     * @see com.nogoodatcoding.commons.ConfigurableEndsWithFileFilter#getInstance(java.lang.String)
     *
     */
    public static ConfigurableEndsWithFileFilter getInstance(String extensions, boolean includeFolders, boolean isCaseSensitive)
    {
        ConfigurableEndsWithFileFilter configurableEndsWithFileFilterToReturn = null;
        //if null, or empty/only whitespace, we'll return a null object
        //so that the overhead of calling accept when we know everything
        //will match is avoided
        if(extensions == null || extensions.trim().isEmpty())
        {
            log.debug("extensions was null or 0 length; do not require any FileFilter, returning null");
        }
        else
        {
            configurableEndsWithFileFilterToReturn = new ConfigurableEndsWithFileFilter(extensions, isCaseSensitive);
            configurableEndsWithFileFilterToReturn.includeFolders = includeFolders;
            configurableEndsWithFileFilterToReturn.isCaseSensitive = isCaseSensitive;
        }

        return configurableEndsWithFileFilterToReturn;
    }

    /**
     *
     * Convenience method to call
     * {@link ConfigurableEndsWithFileFilter#getInstance(java.lang.String, boolean, boolean)}.
     *
     * @param extensions A list of PSV (pipe separated values) of extensions
     *                   that should be accepted by this filter.
     *                   If it's null/empty/only whitespace, a null will be
     *                   returned.
     *                   Any whitespace before and after the pipe will be
     *                   ignored. The extensions should not be in the format of
     *                   {@code *.avi| *.txt | *.java} etc. The asterisks and
     *                   period symbols will treated as literals. Use the format
     *                   {@code avi| txt|java} instead
     *
     * @return null if extensions is null or empty; a 
     *         {@code ConfigurableEndsWithFileFilter} object otherwise
     *
     */
    public static ConfigurableEndsWithFileFilter getInstance(String extensions)
    {
        return ConfigurableEndsWithFileFilter.getInstance(extensions, true, true);
    }

    /**
     *
     * Private constructor so that we can check for empty/null as the extenions
     * to accept and return a null object to avoid overhead where all files will
     * match.
     *
     * @param extensions list of PSV (pipe separated values) of extensions that
     *                   should be accepted by this filter. Will never be
     *                   null/empty; {@code getInstance()} will take care of
     *                   that
     *
     * @param isCaseSensitive If {@code true}, it means that later, comparisons
     *                        will be done with lower case filename, so all
     *                        extensions will be converted to lower case as well
     *
     */
    private ConfigurableEndsWithFileFilter(String extensions, boolean isCaseSensitive)
    {
        log.debug("Splitting PSV list into list of extensions");
        arrayOfExtensions = extensions.split("\\s*\\|\\s*");

        if(isCaseSensitive)
        {
            for(int i = 0; i < arrayOfExtensions.length; i++)
            {
                arrayOfExtensions[i] = arrayOfExtensions[i].toLowerCase();
            }
        }
    }

    public boolean accept(File file)
    {
        String name = null;
        
        if(isCaseSensitive)
        {
            name = file.getName();
        }
        else
        {
            name = file.getName().toLowerCase();
        }
        boolean result = false;

        log.debug("Filename is " + name);

        if(file.isDirectory() && includeFolders)
        {
            return true;
        }

        for(String currentExtension : arrayOfExtensions)
        {
            log.debug("Checking if file has extension " + currentExtension);
            if(name.endsWith(currentExtension))
            {
                result=true;
                break;
            }
        }
        return result;
    }
}